package com.fc.im.netty.codec;

import com.fc.im.netty.exception.HeaderCheckFailedException;
import com.fc.im.netty.message.Message;
import com.fc.im.netty.util.ChannelUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;

/**
 * Created by ChanJiabo on 2017/1/17.
 */
public class MessageDecoder extends LengthFieldBasedFrameDecoder{

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageDecoder.class);

    private static final int DEFAULT_MAX_LENGTH = Short.MAX_VALUE;

    public MessageDecoder(){
        super(DEFAULT_MAX_LENGTH,2,2,0,4);
    }

    @Override
    public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = null;
        try{
            frame = (ByteBuf) super.decode(ctx, in);
            if (null == frame) {
                return null;
            }
            ByteBuffer byteBuffer = frame.nioBuffer();
            return Message.createMessage(byteBuffer);
        }catch (HeaderCheckFailedException e) {
            LOGGER.error(e.getMessage(), e);
            ChannelUtil.closeChannel(ctx.channel());
        }catch (Exception e) {
            LOGGER.error("decode exception, " + ChannelUtil.parseChannelRemoteAddr(ctx.channel()), e);
            ChannelUtil.closeChannel(ctx.channel());
        }finally {
            if (null != frame){
                frame.release();
            }
        }
        return null;
    }
}
